import engine from 'store';
import store from '@/store';
import {
  decimalToFixed
} from "./decimal";

// Store
export const sessionStorage = engine.createStore([
  require('store/storages/sessionStorage')
]);

export const localStorage = engine.createStore([
  require('store/storages/localStorage')
]);

// 获取字符长度
export function getStrLen(str) {
  let count = 0,
    len = String(str).length;
  if (len) {
    for (let i = 0; i < len; i++) {
      if (String(str).charCodeAt(i) > 255) {
        count += 2;
      } else {
        count++;
      }
    }
  }
  return count;
}

// 生产随机数&字母
export function getRandomStr(len) {
  let ret = "";
  for (; ret.length < len; ret += Math.random().toString(36).substr(2));
  return ret.substr(0, len);
}

/**
 * 拆分账号名称、登录账号
 * @param {string} account 待拆分的账号，例如：admin(admin@kyhd.com)
 * @returns {object} {name: "admin", email: "admin@kyhd.com"}
 */
export function splitAccount(account) {
  let ret = account.match(/([^()]+)/g);
  return {
    name: ret[0],
    email: ret[1]
  };
}

/**
 * 根据路由生成左侧菜单
 * @param {string} modName 某个路由模块的name
 * @param {string} pageName 某个页面路由的name
 */
export function createAsideMenu(modName, pageName) {
  let menu = store.state.ROUTES.find(item => {
    return item.name === modName;
  });
  let ret = [];
  if (menu) {
    menu.children.forEach(child => {
      if (child.meta && child.meta.menu) {
        if (!child.meta.permission ||
          (child.meta.permission && hasPermission([child.meta.permission]))) {
          ret.push({
            name: child.meta.menu,
            pathName: child.name,
            icon: child.meta.icon,
            isActive: child.name === pageName
          });
        }
      }
    })
  }
  return ret;
}

/**
 * 生成路由，重定向
 */
export function redirectRoutes(routes = []) {
  routes.forEach(route => {
    // 设置父路由默认重定向
    if (route.children && route.children.length) {
      for (let item of route.children) {
        if (!item.meta || !item.meta.permission || (item.meta.permission && hasPermission([item.meta.permission]))) {
          route.redirect = {
            name: item.name
          };
          break;
        }
      }
    }
  });
  return routes;
}
// 下拉value对应的label
export function mapValue(data, value) {
  let item = data.find(item => item.value === value);
  if (item) {
    return item.label;
  }
  return "";
}

// 文件大小转换
export function kb2mb(v) {
  if (v < 1024) {
    return `${v}KB`;
  } else {
    return `${decimalToFixed(v / 1024, 1)}MB`;
  }
}

export function mb2kb(v) {
  return `${Math.ceil(v * 1024)}KB`
}

// 是否图片
export function isPicture(url) {
  return /\.(jpg|jpeg|png|gif)$/.test(url);
}

// 是否视频
export function isVideo(url) {
  return /\.(mp4)$/.test(url);
}

// 时间折行显示
export function formatMultiLineTime(str) {
  return str.replace(/\s/, "<br>");
}

// 建议出价增加盈利比
export function extraSuggestPrice(v) {
  let user = sessionStorage.get("USER");
  let scale = user.profitPercentage / 100;
  let price = scale === 1 ? v * 11 : v / (1 - scale); // 盈利比
  let ret = decimalToFixed(price, 2);
  return ret < 4 ? 4 : ret; // 最小出价4块
}

// 建议出价
export function suggestPrice(str) {
  if (!str) return "";
  let range = str.split("~"),
    min = extraSuggestPrice(range[0]),
    max = extraSuggestPrice(range[1]),
    price = decimalToFixed(max * 1.1, 2); // 出价上浮10%
  return `底价范围：${min}-${max}元，建议出价：${price}元`;
}

// 秒转时分秒
export function formatSeconds(v) {
  let n = Math.ceil(v),
    h = Math.floor(n / 3600),
    m = Math.floor((n - h * 60) / 60),
    sec = n - h * 3600 - m * 60;
  if (h > 0) {
    return `${h}小时${m}分${sec}秒`;
  } else if (m > 0) {
    return `${m}分${sec}秒`;
  }
  return `${sec}秒`;
}

/**
 * 功能是否有权限
 */
export function hasPermission(value = []) {
  // 没有权限控制
  if (!value.length) return true;
  let user = sessionStorage.get("USER");
  let permissions = user.permission || [];
  return value.some(p => permissions.includes(p));
}

// 获取要跳转的首页
// moduleName是空，默认找全部模块
export function getHome(moduleName) {
  // 动态跳转首页
  let user = sessionStorage.get("USER");
  let permissions = user.permission || [];
  let map = {
    home_manage_page: "home",
    account_advertiser_page: "account-advertiser-man",
    account_admin_page: "account-admin-man",
    promote_page: "generalize-plan",
    data_advertiser_page: "data-advertiser",
    data_user_page: "data-total",
    data_plan_page: "data-plan",
    data_unit_page: "data-cell",
    data_creative_page: "data-creative",
    financial_manage_page: "finance-man",
    financial_transfer_page: "finance-transfer-man",
    financial_transferDetail_page: "finance-transfer-detail",
    financial_adxConsum_page: "finance-adx-expend",
    other_aptitudeAudit_page: "other-account-audit",
    other_creativeAudit_page: "other-creative-audit",
    other_permissionsManage_page: "other-role",
    // other_templateManage_page: "other-template"
  };
  let key = Object.keys(map).find(page => {
    if (moduleName) {
      if (page.startsWith(moduleName)) {
        return permissions.includes(page)
      }
    } else {
      return permissions.includes(page)
    }
  });
  if (key) {
    return map[key];
  }
  return "";
}

// 上传文件格式
// @param format {string}  "png,jpg,gif,mp4"
export function isUploadFormat(format, name) {
  return format.split(",").some(item => {
    return name.endsWith(item);
  });
}
// 截取上传文件名称
export function getUploadFileName(url) {
  return url.match(/[^/]+$/g)[0];
}
// 获取图片文件
export function getUploadImage(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onload = () => {
      let image = new Image();
      image.onload = () => {
        resolve({
          image,
          width: image.width,
          height: image.height
        });
      };
      image.onerror = () => {
        reject({
          image: null,
          width: 0,
          height: 0
        });
      };
      image.src = reader.result;
    };
    reader.readAsDataURL(file);
  });
}